package com.itcast.cn.conversation.controller;

import com.itcast.cn.conversation.pojo.User;
import com.itcast.cn.conversation.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 注册
 *
 * @author hyatt
 */
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数中的验证码
        String checkCode = request.getParameter("checkCode");

        // 判断输入的验证码和生成的验证码是否一致
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        if (checkCodeGen.equalsIgnoreCase(checkCode)) {
            // 获取参数中的用户名和密码并包装成User对象
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            // 判断用户名是否存在
            User user1 = userService.selectByUsername(username);
            if (user1 == null) {
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                // 添加用户
                userService.add(user);
                // 跳转登陆页面
                String contextPath = request.getContextPath();
                response.sendRedirect(contextPath + "/login.jsp");
            } else {
                // 注册失败
                request.setAttribute("errorMsg", "用户名已存在");
                // 跳转到register
                request.getRequestDispatcher("/register.jsp").forward(request, response);
            }
        } else {
            // 注册失败
            request.setAttribute("errorMsg", "验证码错误");
            // 跳转到register
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
